package 计时器;


import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

class Taske implements Comparable<Taske>{
    //任务
    private Runnable runnable;
    //时间
    private long time;

    public Taske(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }
    @Override
    public int compareTo(Taske o) {
        return (int)(this.getTime()-o.getTime());
    }
}
public class MyTimer  {
    //优先级队列，将时间快的出队  存放任务
    private BlockingQueue<Taske> queue=new PriorityBlockingQueue<>();

    //扫描线程
    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                synchronized (this) {
                    //扫描操作
                    try {
                        //出队
                        Taske taske = queue.take();
                        long time = taske.getTime();
                        if (System.currentTimeMillis() >= time) {
                            //执行任务
                            taske.getRunnable().run();
                        } else {
                            //没达到时间重新入队
                            queue.put(taske);

                            this.wait(time - System.currentTimeMillis());
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }



    //schedule方法
    public void schedule(Runnable runnable,long time) throws InterruptedException {
        //传入参数后要执行
        Taske taske=new Taske(runnable,time);
        queue.put(taske);
        synchronized (this){
            this.notify();
        }
    }



}
